package com.gouaixin.bee.beeframework2.extra.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;


/**
 * 网络帮助类 接受和传递的都是JSON数据
 * 
 * @author guodan
 * @date 2015-3-30 上午9:52:27
 */
public class HttpUtil {
	private static final HttpUtil util = new HttpUtil();
	private static final String SIGNUP_URL = "https://walnut-sys.net:8001/api/v1/signup";
	private static final String LOGIN_URL = "https://walnut-sys.net:8001/api/v1/login";
	private static final String RESETPASS_URL = "https://walnut-sys.net:8001/api/v1/resetpassword";
	private static final String LOGOUT_URL = "https://walnut-sys.net:8001/api/v1/logout";
	private static final String SETCLOCK_URL = "https://walnut-sys.net:8001/api/v1/setbabyclock";
	private static final String ADDBABY_URL = "https://walnut-sys.net:8001/api/v1/bb/addbaby";
	private static final String GETBABY_URL = "https://walnut-sys.net:8001/api/v1/bb/getbabies";
	private static final String BIND_URL = "https://walnut-sys.net:8001/api/v1/bb/bind";
	private static final String UNBIND_URL = "https://walnut-sys.net:8001/api/v1/bb/unbind";
	private static final String GETDEVICE_URL = "https://walnut-sys.net:8001/api/v1/getdevices";
	private static final String Feedhistory_URL = "https://walnut-sys.net:8001/api/v1/feedhistory1";
	private static final String GETFeedhistory1_URL = "https://walnut-sys.net:8001/api/v1/feedhistory2";
	private static final String GETFeedhistory2_URL = "https://walnut-sys.net:8001/api/v1/feedhistory3";

	private static final String TAG = "main";

	private HttpUtil() {
	}

	public static HttpUtil getInstance() {
		return util;
	}

	public static synchronized String doHttpsPost(Context context,String serverURL,
			String jsonStr, boolean isNeedToken) throws Exception {
		// 参数
		HttpParams httpParameters = new BasicHttpParams();
		// 设置连接超时
		HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
		// 设置socket超时
		HttpConnectionParams.setSoTimeout(httpParameters, 100000);
		// 获取HttpClient对象 （认证）
		HttpClient hc = MyClientUtil.initHttpClient(context,httpParameters);
		HttpPost post = new HttpPost(serverURL);
		// // 发送数据类型
		post.addHeader("Content-Type", "application/json");
		// 接受数据类型
		post.addHeader("Accept", "application/json");
		if (isNeedToken) {
			post.addHeader("Authorization", "Token " + getToken(context));
		}
		// 绑定到请求 Entry
		StringEntity se = new StringEntity(jsonStr, "utf-8");
		post.setEntity(se);
		post.setParams(httpParameters);
		HttpResponse response = null;
		try {
			response = hc.execute(post);
		} catch (UnknownHostException e) {
			throw new Exception("Unable to access " + e.getLocalizedMessage());
		} catch (SocketException e) {
			e.printStackTrace();
		}
		int sCode = response.getStatusLine().getStatusCode();
		String result = EntityUtils.toString(response.getEntity());
		if (sCode == HttpStatus.SC_OK || sCode == HttpStatus.SC_CREATED) {
			Log.e("result ok", result);
			return result;

		} else
			Log.e("result fail", result);
		throw new Exception("StatusCode is " + sCode);
	}

	

	/**
	 * GET请求
	 */
	public String doGetReq(Context context,String url, List<NameValuePair> params) {
		StringBuffer sb = new StringBuffer();
		HttpClient client = null;
		String url2 = null;

		if (params == null || params.size() == 0) {
			url2 = url;
		} else {
			url2 = url + "?" + URLEncodedUtils.format(params, HTTP.UTF_8);
		}
		try {
			// 参数
			HttpParams httpParameters = new BasicHttpParams();
			// 设置连接超时
			HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
			// 设置socket超时
			HttpConnectionParams.setSoTimeout(httpParameters, 20000);
			// 获取HttpClient对象 （认证）
			client = MyClientUtil.initHttpClient(context,httpParameters);
			HttpGet get = new HttpGet(url2);
			get.addHeader("Authorization", "Token " + getToken(context));

			HttpResponse response = null;
			response = client.execute(get);
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						entity.getContent()));
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				// System.err.println("result :" + sb.toString());
				// Log.v(CoolmalApp.TAG, "数据获取成功");
				return sb.toString();
			} else {
				Log.v(TAG, "操作失败");
			}

		} catch (Exception e) {
			System.out.println("出现异常：" + e.getMessage());
		} finally {
			if (client != null) {
				client.getConnectionManager().shutdown();
			}
		}
		return null;
	}


	/**
	 * setting clock
	 */
	public String doSetClock(Context context,String data) throws Exception {

		return doHttpsPost(context,SETCLOCK_URL, data, true);
	}



	public static String getToken(Context context) {
		SharedPreferences token =context.getSharedPreferences(
				"token", 0);
		String accessToken = token.getString("accessToken", "");
		return accessToken;
	}
}
